package com.sky.controller.admin;

import com.sky.config.MinioConfig;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Resource
    private MinioUtil minioUtil;

    private String bucket = "jichi";


    @SneakyThrows
    public void createBucket(String bucket) {
        minioUtil.createBucket(bucket);
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(
            @RequestParam("file") MultipartFile file// 明确指定参数名
            ) throws Exception { // 添加参数校验注解
        log.info("文件上传：{}", file.getOriginalFilename()); // 打印真实文件名
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构造新文件名
        String objectName = UUID.randomUUID().toString() + extension;

        minioUtil.uploadFile(file.getInputStream(),bucket,objectName+"/"+file.getName());

        // 返回文件访问路径
        return Result.success(new StringBuilder("https://").append(bucket)
                .append(".")
                .append(objectName)
                .append("/")
                .append(file.getName()).toString());
    }
}
